/**
 * 2017年12月20日
 */
package com.cmwa.solution.sys.msg.filter.filters;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.cmwa.solution.sys.msg.dao.IMsgSendDao;
import com.cmwa.solution.sys.msg.filter.MsgFilter;
import com.cmwa.solution.sys.msg.filter.MsgFilterChain;
import com.cmwa.solution.sys.msg.filter.MsgFilterResult;
import com.cmwa.solution.sys.msg.filter.enums.MsgFilterCodeEnum;
import com.cmwa.solution.sys.msg.vo.ManualOperationParamsVo;
import com.cmwa.solution.sys.msg.vo.MsgWaitSendVo;
import com.cmwa.solution.utils.JsonUtil;
import com.google.common.base.Joiner;

/**
 * 同一批收件人发送数量过滤
 * @author ex-zuotc
 * 2017年12月20日
 */
@Component("recipientsSendCountFilter")
public class RecipientsSendCountFilter implements MsgFilter {
	private Log logger = LogFactory.getLog(MsgTypeSendCountFilter.class); 
	@Resource
	private IMsgSendDao iMsgSendDao;

	@Override
	public void doFilter(List<MsgWaitSendVo> sendVos, ManualOperationParamsVo params, String filterParam, MsgFilterChain filterChian) {
		logger.error("filterParam:" + filterParam);
		MsgFilterResult msgFilterResult = filterChian.getMsgFilterResult();
		
		@SuppressWarnings("unchecked")
		Map<String, Object> paramMap = JsonUtil.parseJson(filterParam, Map.class);
		// 多少分钟
		Integer minute = (Integer) paramMap.get("minute");
		// 发送数量
		Integer count = (Integer) paramMap.get("count");
		
		for (MsgWaitSendVo sendVo : sendVos) {
			List<String> recipients = sendVo.getRecipients();
			String recipientsStr = Joiner.on(";").join(recipients);
			int sentCount = iMsgSendDao.getEmailRecipientCount(recipientsStr, minute);
			if (sentCount >= count) {
				msgFilterResult.setSendable(false);
				msgFilterResult.setFilterCode(MsgFilterCodeEnum.M008_2);
				msgFilterResult.setMessage("邮件《" + sendVo.getTitle() + "》发送失败，同一批收件人的邮件" + minute + "分钟内发送数量超过" + count + "封，收件人邮箱：" + recipientsStr); 
				return;
			}
		}
		
		// next
		filterChian.doFilter(sendVos, params);
	}


}
